import { Textarea } from "@/components/ui/textarea";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { ListTodo, MessageSquare, Pencil } from "lucide-react";
import { useEffect, useRef, useState } from "react";

type InputMode = "chat" | "task";

interface CommandInputProps {
  onSubmit: (
    content: string,
    mode: InputMode,
    removeEditMessage: boolean
  ) => void;
  onClear: () => void;
  fetchEditMessage: () => string;
}

// 检测操作系统
const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;
const modifierKey = isMac ? "⌘" : "Ctrl";

// 检查修饰键是否匹配当前操作系统
const isCorrectModifierKey = (
  e: KeyboardEvent | React.KeyboardEvent
): boolean => {
  if (isMac) {
    return e.metaKey && !e.ctrlKey; // macOS 只响应 ⌘ 键
  }
  return e.ctrlKey && !e.metaKey; // Windows 只响应 Ctrl 键
};

function ModeToggle({
  mode,
  onToggle,
  editing,
}: {
  mode: InputMode;
  onToggle: (mode: InputMode) => void;
  editing: boolean;
}) {
  const isChat = mode === "chat";

  return (
    <Tooltip>
      <TooltipTrigger>
        <div
          role="button"
          tabIndex={0}
          onClick={() => onToggle(isChat ? "task" : "chat")}
          onKeyDown={(e) =>
            e.key === "Enter" && onToggle(isChat ? "task" : "chat")
          }
          className={cn(
            "inline-flex items-center justify-center size-8",
            "transition-colors rounded-md",
            "hover:bg-accent hover:text-accent-foreground",
            editing && "bg-accent text-accent-foreground"
          )}
        >
          {editing ? (
            <Pencil className="h-4 w-4" />
          ) : (
            <>
              {isChat ? (
                <MessageSquare className="h-4 w-4" />
              ) : (
                <ListTodo className="h-4 w-4" />
              )}
            </>
          )}
        </div>
      </TooltipTrigger>
      <TooltipContent>
        <p>
          {isChat
            ? `切换到任务模式 (${modifierKey}2)`
            : `切换到聊天模式 (${modifierKey}1)`}
        </p>
      </TooltipContent>
    </Tooltip>
  );
}

export function CommandInput({
  onSubmit,
  onClear,
  fetchEditMessage,
}: CommandInputProps) {
  const [input, setInput] = useState("");
  const [editing, setEditing] = useState(false);
  const [mode, setMode] = useState<InputMode>("chat");
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 自动调整高度
  useEffect(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    textarea.style.height = "40px"; // 重置为初始高度
    const scrollHeight = textarea.scrollHeight;
    textarea.style.height = `${Math.min(scrollHeight, 200)}px`;
  }, [input]);

  // 监听全局快捷键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isCorrectModifierKey(e)) return;

      switch (e.key) {
        case "1":
          e.preventDefault();
          setMode("chat");
          break;
        case "2":
          e.preventDefault();
          setMode("task");
          break;
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim()) return;

    onSubmit(input, mode, editing);
    setInput("");
    setEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Escape" && editing) {
      setEditing(false);
      return;
    }

    // 处理编辑快捷键
    if (e.key === "ArrowUp") {
      e.preventDefault();
      setInput(fetchEditMessage());
      setEditing(true);
      return;
    }

    // 处理清除快捷键
    if (e.key.toLowerCase() === "l" && e.ctrlKey) {
      e.preventDefault();
      onClear();
      return;
    }

    // 处理提交快捷键
    if (e.key === "Enter" && isCorrectModifierKey(e)) {
      e.preventDefault();
      handleSubmit(e);
      return;
    }

    // 单独按 enter 换行
    if (e.key === "Enter" && !e.shiftKey) {
      // 不阻止默认行为，允许换行
      return;
    }
  };

  return (
    <div className="border-t border-border p-4 bg-background">
      <form onSubmit={handleSubmit} className="relative">
        <div className="absolute left-2 top-1/2 -translate-y-1/2 z-10">
          <TooltipProvider>
            <ModeToggle mode={mode} onToggle={setMode} editing={editing} />
          </TooltipProvider>
        </div>
        <Textarea
          ref={textareaRef}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={
            mode === "chat"
              ? `输入消息... (${modifierKey}↵ 发送)`
              : `添加新任务... (${modifierKey}↵ 添加)`
          }
          className={cn(
            "flex-1 resize-none",
            "min-h-[40px] max-h-[200px]",
            "pl-10 pr-3 py-2", // 减小左侧内边距
            "scrollbar-thin scrollbar-thumb-border scrollbar-track-background"
          )}
        />
      </form>
    </div>
  );
}
